/**
 * @class UI组件-网络加载遮罩
 * @author DuskyHuang 圣子
*/

import { _decorator, Node } from 'cc';
import { __cfw_notifications__ } from '../configs';
import { tip } from '../utils';
import BaseUI from './base';
import { inner } from '../core/boot';
const { ccclass } = _decorator;

function showTimeout(this: NetCover) { return this.timeoutClear; }
function autoRotate(this: NetCover) { return this.autoRotateSign; }

@ccclass('cfw.NetCover')
export class NetCover extends BaseUI {

    @tip("出现延迟", [0, 5, 0.1], ["unit", "sec"]) public delay: time.sec = 0.5;
    @tip("超时移除") public timeoutClear: boolean = true;
    @tip("超时时长", showTimeout, [1, 30, 1], ["unit", "sec"]) public timeout: time.sec = 5;
    @tip("自动旋转") public autoRotateSign: boolean = false;
    @tip("旋转图标", Node, autoRotate) public sign: Node = null;
    @tip("旋转图标", autoRotate) public antiClockwise: boolean = false;
    @tip("旋转周期", autoRotate, [1, 30, 0.1], ["unit", "sec"]) public period: time.sec = 1;

    protected onLoad(): void { inner.dispatch(__cfw_notifications__.UI.REGISTER, this); }
    protected onDestroy(): void { inner.dispatch(__cfw_notifications__.UI.UNREGISTER, this); }

    protected lateUpdate(dt: time.sec): void {
        if (this.autoRotateSign && this.sign && this.period > 0) {
            this.sign.angle += (this.antiClockwise ? 360 : -360) * (dt / this.period);
        }
    }

    protected start(): void {
        this.node.active = false;
    }

    public show(): void {
        this.unscheduleAllCallbacks();
        super.show();
        if (this.delay >= 0) {
            this.activateChildren = false;
            this.scheduleOnce(() => this.activateChildren = true, this.delay);
        } else this.activateChildren = true;
        if (this.timeoutClear) {
            this.scheduleOnce(() => this.hide(), this.timeout);
        }
    }

    public hide(): void {
        this.unscheduleAllCallbacks();
        super.hide();
    }

    public set activateChildren(show: boolean) {
        this.node.children.forEach(child => child.active = show);
    }
}